package com.liang.codegenerate.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.liang.codegenerate.common.ErrorCode;
import com.liang.codegenerate.exception.BusinessException;
import com.liang.codegenerate.mapper.FieldsMapper;
import com.liang.codegenerate.model.dto.tables.TableTestJoinDto;
import com.liang.codegenerate.model.dto.tables.TablesAddDto;
import com.liang.codegenerate.model.dto.tables.TablesListDto;
import com.liang.codegenerate.model.dto.tables.TablesUpdateDto;
import com.liang.codegenerate.model.entity.Fields;
import com.liang.codegenerate.model.entity.Tables;
import com.liang.codegenerate.model.entity.User;
import com.liang.codegenerate.model.vo.tables.TableJoinTestVo;
import com.liang.codegenerate.model.vo.tables.TablesFieldsVo;
import com.liang.codegenerate.service.TablesService;
import com.liang.codegenerate.mapper.TablesMapper;
import com.liang.codegenerate.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @author lzw
 * @description 针对表【tables】的数据库操作Service实现
 * @createDate 2024-01-20 21:08:33
 */
@Service
public class TablesServiceImpl extends ServiceImpl<TablesMapper, Tables>
        implements TablesService {

    @Resource
    private TablesMapper tablesMapper;

    @Resource
    private UserService userService;

    @Resource
    private FieldsMapper fieldsMapper;

    @Override
    public boolean addTable(TablesAddDto tablesAddDto, HttpServletRequest request) {
        String tableName = tablesAddDto.getTablesName();
        String tableComment = tablesAddDto.getTablesComment();
        String tableTag = tablesAddDto.getTablesTag();
        Integer tablesType = tablesAddDto.getTablesType();

        if (StringUtils.isAnyBlank(tableComment, tableName, tableTag)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        if (tablesType == null || (tablesType != 0 && tablesType != 1)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        User loginUser = userService.getLoginUser(request);
        Tables tables = new Tables();
        BeanUtils.copyProperties(tablesAddDto, tables);
        tables.setCreateBy(loginUser.getUserName());

        return this.save(tables);
    }

    @Override
    public int deleteTable(Long id) {
        int i = tablesMapper.deleteById(id);
        int tablesId = 1;
        if (i > 0) {
            tablesId = fieldsMapper.delete(new QueryWrapper<Fields>().eq("tables_id", id));
        }
        return tablesId;
    }

    @Override
    public boolean updateTable(TablesUpdateDto tablesUpdateDto) {
        Tables tables = tablesMapper.selectById(tablesUpdateDto.getId());
        BeanUtils.copyProperties(tablesUpdateDto, tables);
        int i = tablesMapper.updateById(tables);
        if (i <= 0){
            throw new BusinessException(ErrorCode.OPERATION_ERROR);
        }
        return true;
    }

    @Override
    public List<Tables> listTable(TablesListDto tablesListDto, HttpServletRequest request) {

        User loginUser = userService.getLoginUser(request);
        QueryWrapper<Tables> queryWrapper = new QueryWrapper<>();

        queryWrapper.like(StringUtils.isNotBlank(tablesListDto.getTablesName()),
                "tables_name",
                tablesListDto.getTablesName());
        queryWrapper.like(StringUtils.isNotBlank(tablesListDto.getTablesTag()),
                "tables_tag",
                tablesListDto.getTablesTag());
        queryWrapper.like(StringUtils.isNotBlank(tablesListDto.getTablesComment()),
                "tables_comment",
                tablesListDto.getTablesComment());
        // 类型为全部时
        if (tablesListDto.getTablesType() == null){
            // 查询公有的和自己私有的
            queryWrapper.eq("tables_type", 1).or().eq("create_by", loginUser.getUserName());
        }else {
            if (tablesListDto.getTablesType() == 0){
                queryWrapper.eq("tables_type", tablesListDto.getTablesType()).eq("create_by", loginUser.getUserName());
            }
            if (tablesListDto.getTablesType() == 1){
                queryWrapper.eq("tables_type", tablesListDto.getTablesType());
            }
        }

        return tablesMapper.selectList(queryWrapper);
    }

    @Override
    public TableJoinTestVo testJoin(TableTestJoinDto tableTestJoinDto) {

        String address = tableTestJoinDto.getAddress();
        String userName = tableTestJoinDto.getUserName();
        String password = tableTestJoinDto.getPassword();
        String dataBase = tableTestJoinDto.getDataBase();

        if (StringUtils.isAnyBlank(address, userName, dataBase)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        DriverManagerDataSource dataSource = getConnection(address, userName, password, dataBase);

        List<String> tableNames;
        try {
            JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
            tableNames = jdbcTemplate.queryForList("SHOW TABLES", String.class);
        } catch (DataAccessException e) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR);
        }

        TableJoinTestVo tableJoinTestVo = new TableJoinTestVo();
        tableJoinTestVo.setTablesName(tableNames);
        tableJoinTestVo.setIsSuccess(true);
        return tableJoinTestVo;
    }

    @Override
    public Tables listTableById(Long id) {
        QueryWrapper<Tables> tablesQueryWrapper = new QueryWrapper<>();
        tablesQueryWrapper.eq("id",id);
        return tablesMapper.selectOne(tablesQueryWrapper);
    }

    @Override
    public TablesFieldsVo getFields(Long id) {
        QueryWrapper<Tables> tablesQueryWrapper = new QueryWrapper<>();
        tablesQueryWrapper.eq("id",id);
        Tables tables = tablesMapper.selectOne(tablesQueryWrapper);
        if (tables == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        TablesFieldsVo tablesFieldsVo = new TablesFieldsVo();
        tablesFieldsVo.setTables(tables);
        QueryWrapper<Fields> fieldsQueryWrapper = new QueryWrapper<>();
        fieldsQueryWrapper.eq("tables_id", id);
        List<Fields> fields = fieldsMapper.selectList(fieldsQueryWrapper);
        tablesFieldsVo.setFieldsList(fields);
        return tablesFieldsVo;
    }

    /**
     * 根据数据库连接信息，获取数据库连接
     *
     * @param address  地址
     * @param userName 用户名
     * @param password 密码
     * @param dataBase 数据库
     * @return 连接
     */

    public DriverManagerDataSource getConnection(String address, String userName, String password, String dataBase) {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        try {
            dataSource.setDriverClassName("com.mysql.jdbc.Driver");
            dataSource.setUrl("jdbc:mysql://" + address + "/" + dataBase + "?useUnicode=true&characterEncoding=utf8&useSSL=false");
            dataSource.setUsername(userName);
            dataSource.setPassword(password);
        } catch (Exception e) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR);
        }
        return dataSource;
    }
}




